package com.example.eos.service;

import com.example.eos.tool.GlobalParam;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class FilesService {

    //文件上传
    public String uploadFile(MultipartFile file, String filepath){
        if(file.isEmpty()){
            return "";
        }
        //获取文件名
        String filename = file.getOriginalFilename();
        //获取文件类型
        assert filename != null;
        String filetype = filename.substring(filename.indexOf("."));
        if(GlobalParam.getUploadPath()==null){
            return "";
        }
        filepath = GlobalParam.getUploadPath()+"/"+filepath+filetype;
        System.out.println("文件路径:"+filepath);
        File dest = new File(filepath);
        //创建父文件目录
        if(!dest.getParentFile().exists()){
            if(!dest.getParentFile().mkdirs()){
                return "";
            }
        }
        try{
            file.transferTo(dest);
        }catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return "";
        }
        return filepath;
    }

    //文件删除
    public Boolean deleteFile(String filepath){
        File file = new File(filepath);
        return file.exists()&&file.delete();
    }

}
